package com.yuanfeng.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.activity.dto.*;
import com.yuanfeng.activity.entity.ActivitySeckillBaseEntity;
import com.yuanfeng.activity.entity.ActivitySeckillGoodsEntity;
import com.yuanfeng.activity.mapper.ActivitySeckillBaseMapper;
import com.yuanfeng.activity.mapper.ActivitySeckillGoodsMapper;
import com.yuanfeng.activity.service.ActivitySeckillBaseService;
import com.yuanfeng.activity.service.ActivitySeckillGoodsService;
import com.yuanfeng.activity.vo.GdbSeckillBaseVO;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.dto.goods.ManageSeckillBaseUpdateDTO;
import com.yuanfeng.commoms.dto.goods.SeckillGoodsDTO;
import com.yuanfeng.commoms.dto.goods.SeckillGoodsListDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.goods.SeckillGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName ActivitySeckillBaseServiceImpl
 * @Description  限时秒杀活动表
 * @Author ty
 * @Date 2023-07-04 17:26:46
 * @Version 1.0
 **/
@Service
public class ActivitySeckillBaseServiceImpl extends ServiceImpl<ActivitySeckillBaseMapper, ActivitySeckillBaseEntity>
        implements ActivitySeckillBaseService {

    @Autowired
    private ActivitySeckillGoodsMapper activitySeckillGoodsMapper;

    @Autowired
    private ActivitySeckillGoodsService activitySeckillGoodsService;
    @Override
    public ResponseResult getList(FinishTimeSecondkillDTO param) {
        Map map = null;
        try {
            map = ParseMapUtils.beanToMap(param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        IPage<Map<String,Object>> iPage = this.baseMapper.selectFinishTimeSecondkillPojo(new Query<Map<String,Object>>().getPage(map), param);
        return ResponseResult.success(PageUtils.getPage(iPage));
    }

    @Override
    public ResponseResult getByPage(FinishTimeSecondkillDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        if(userInfo.getShopId()==null){
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        Integer shopId = Integer.valueOf(userInfo.getShopId());
        param.setShopId(shopId);
        Map map = null;
        try {
            map = ParseMapUtils.beanToMap(param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        IPage<Map<String,Object>> iPage = this.baseMapper.getByPage(new Query<Map<String,Object>>().getPage(map), param);
        return ResponseResult.success(PageUtils.getPage(iPage));
    }

    @Override
    public ResponseResult deleteData(SecondKillGoodsDTO param) {
        this.baseMapper.deleteById(param.getSeckillId());

        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryShopSeckillBase(ManageSeckillBaseQueryDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        GdbSeckillBaseVO result = this.baseMapper.selectByPrimaryKey(param.getSeckillId());
        return ResponseResult.success(result);
    }
    @Override
    public ResponseResult deleteShopSeckillBase(Map<String, Object> param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_SECKILL, param.get("token").toString());

        if (userPermissionsResult.getFlag()) {

            List<Integer> commonIdList =activitySeckillGoodsMapper.selectList(new LambdaQueryWrapper<ActivitySeckillGoodsEntity>()
                                       .eq(ActivitySeckillGoodsEntity::getSeckillId, param.get("seckillId").toString()))
                                       .stream().map(ActivitySeckillGoodsEntity::getCommonId).collect(Collectors.toList());


            if (!CollectionUtils.isEmpty(commonIdList)) {
                if (!CollectionUtils.isEmpty(commonIdList)) {
                    // 获取其他正在进行的活动
                    List<Integer> activeCommonIdList = activitySeckillGoodsMapper.selectActiveSeckillGoods(param.get("seckillId").toString(),null);
                    if(!CollectionUtils.isEmpty(activeCommonIdList)){
                        activitySeckillGoodsMapper.updateCommonIsXian2(commonIdList);
                    }

                }
            }

            activitySeckillGoodsMapper.delete(new LambdaQueryWrapper<ActivitySeckillGoodsEntity>()
                                      .eq(ActivitySeckillGoodsEntity::getSeckillId, param.get("seckillId").toString()));
            this.baseMapper.deleteById(param.get("seckillId").toString());

        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryShopSeckilCopy(Map<String, Object> param) {
        // 权限判断
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(String.valueOf(param.get("token")));

        if (userInfoVO != null) {
            //查询秒杀活动信息
            ManageSeckillBaseUpdateDTO seckillBase = this.baseMapper.selectSeckilById(Integer.valueOf(param.get("seckillId").toString()));
            //查询商品信息
            List<SeckillGoodsListDTO> seckillGoodsList = this.baseMapper.selectSeckilGoodsById(Integer.valueOf(param.get("seckillId").toString()));
            List<SeckillGoodsListDTO> seckillGoods = new ArrayList<>();
            if(null != seckillGoodsList && seckillGoodsList.size() > 0){

                Map<Object, List<SeckillGoodsListDTO>> listMap = seckillGoodsList.stream().collect(Collectors.groupingBy(item -> {
                    return item.getCommonId();
                }));
                for (Map.Entry<Object, List<SeckillGoodsListDTO>> entry : listMap.entrySet()) {
                    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
                    List<SeckillGoodsListDTO> value = entry.getValue();
                    SeckillGoodsListDTO goodsVO = new SeckillGoodsListDTO();
                    goodsVO.setGoodsName(value.get(0).getGoodsName());
                    goodsVO.setGoodsImage(value.get(0).getGoodsImage());
                    goodsVO.setGoodsPrice(value.get(0).getGoodsPrice());
                    goodsVO.setCommonId(value.get(0).getCommonId());
                    goodsVO.setGoodsUpperLimit(value.get(0).getGoodsUpperLimit());
                    BigDecimal seckillMaxPrice = value.get(0).getSeckillPrice();
                    BigDecimal seckillMinPrice = value.get(0).getSeckillPrice();
                    Integer seckillAllNum = 0;
                    List<SeckillGoodsDTO> seckillGoodsDTOS = new ArrayList<>();
                    for (SeckillGoodsListDTO seckillGoodsListDTO : value) {
                        SeckillGoodsDTO seckillGoodsDTO = new SeckillGoodsDTO();
                        seckillGoodsDTO.setCommonId(seckillGoodsListDTO.getCommonId());
                        seckillGoodsDTO.setGoodsId(seckillGoodsListDTO.getGoodsId());
                        seckillGoodsDTO.setGoodsPrice(seckillGoodsListDTO.getGoodsPrice());
                        seckillGoodsDTO.setSeckillPrice(seckillGoodsListDTO.getSeckillPrice());
                        seckillGoodsDTO.setSeckillNum(seckillGoodsListDTO.getSeckillNum());
                        seckillAllNum = seckillAllNum + seckillGoodsListDTO.getSeckillNum();
                        if(seckillMaxPrice.compareTo(seckillGoodsListDTO.getSeckillPrice()) > 0 ){
                            seckillMinPrice = seckillGoodsListDTO.getSeckillPrice();
                        }else{
                            seckillMaxPrice = seckillGoodsListDTO.getSeckillPrice();
                        }
                        seckillGoodsDTOS.add(seckillGoodsDTO);
                    }
                    goodsVO.setSeckillMaxPrice(seckillMaxPrice);
                    goodsVO.setSeckillMinPrice(seckillMinPrice);
                    goodsVO.setSeckillAllNum(seckillAllNum);
                    goodsVO.setSpecLists(seckillGoodsDTOS);
                    seckillGoods.add(goodsVO);
                }
            }
            seckillBase.setSeckillGoodsList(seckillGoods);
            return ResponseResult.success(seckillBase);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
    }

    @Override
    public ResponseResult queryShopSeckillBaseList(ManageSeckillBaseUpdateDTO param) throws IllegalAccessException {

        List<ActivitySeckillBaseEntity> dataList = Lists.newArrayList();
        Integer totalCount = 0;
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_SECKILL, param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(Integer.valueOf(userPermissionsResult.getShopId()));
            Map data= ParseMapUtils.beanToMap(param);
            IPage<ActivitySeckillBaseEntity> page=this.baseMapper.selectShopSeckillBaseList(new Query<ActivitySeckillBaseEntity>().getPage(data),
                    param);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
    }

    @Override
    public ResponseResult addShopSeckillBase(ManageSeckillBaseUpdateDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_SECKILL, param.getToken());

        if (userPermissionsResult.getFlag()) {
            SeckillGoodsQueryResultVO seckillGoodsQueryResult = new SeckillGoodsQueryResultVO();
            Integer shopId = Integer.valueOf(userPermissionsResult.getShopId());
            String shopName = this.baseMapper.selectShopName(shopId);
            param.setShopName(shopName);
            param.setUserId(userPermissionsResult.getUserId());
            param.setUserNickName(userPermissionsResult.getUserNickname());
            param.setShopId(shopId);
            if(param.getSeckillExplain() == null){
                param.setSeckillExplain("");
            }
            Integer commonIsXian = 0;
            Integer seckillState = 0;
            if(null != param.getSeckillHour() && null != param.getSeckillStartDate()){
                String seKillHourStr = "";
                switch (param.getSeckillHour()){
                    case 1:
                        seKillHourStr = "08:00:00";
                        break;
                    case 2:
                        seKillHourStr = "12:00:00";
                        break;
                    case 3:
                        seKillHourStr = "16:00:00";
                        break;
                    case 4:
                        seKillHourStr = "20:00:00";
                        break;
                    case 5:
                        seKillHourStr = "00:00:00";
                        break;
                    default:
                        seKillHourStr = "00:00:00";
                }
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
                    String seckillStartTime = simpleDateFormat2.format(param.getSeckillStartDate()) + " " + seKillHourStr;
                    param.setSeckillStartTime(simpleDateFormat.parse(seckillStartTime));
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }

            }
            if(new Date().before(param.getSeckillStartTime())){
                param.setSeckillState(0);
                commonIsXian = 0;
                seckillState = 0;
            }else if (DateUtils.belongCalendar(new Date(), param.getSeckillStartTime(), param.getSeckillEndTime())) {
                param.setSeckillState(1);
                commonIsXian = 2;
                seckillState = 1;
            } else {
                param.setSeckillState(2);
                commonIsXian = 0;
                seckillState = 2;
            }

            if(null == param.getSeckillCreateTime()) {
                param.setSeckillCreateTime(new Date());
            }
            SeckillGoodsUpdateDTO goodsParam = new SeckillGoodsUpdateDTO();
            if (null == param.getSeckillId()) {
                if (null == param.getComboId()) {
                    param.setComboId(0);
                }
                this.baseMapper.insertShopSeckillBase(param);
                seckillGoodsQueryResult.setSeckillId(param.getSeckillId());
                goodsParam.setSeckillId(param.getSeckillId());
                goodsParam.setSeckillGoodsList(param.getSeckillGoodsList());
                goodsParam.setToken(param.getToken());
                activitySeckillGoodsService.addShopSeckillGoods(goodsParam);
            } else {
                this.baseMapper.updateShopSeckillBase(param);
                // 查询参与此限时折扣的商品
                List<Integer> commonList = activitySeckillGoodsMapper.selectList(new LambdaQueryWrapper<ActivitySeckillGoodsEntity>()
                                            .eq(ActivitySeckillGoodsEntity::getSeckillId,param.getSeckillId()))
                                            .stream().map(ActivitySeckillGoodsEntity::getCommonId).collect(Collectors.toList());
                CommonIsXianUpdateDTO commonIsXianUpdateParam = new CommonIsXianUpdateDTO();
                // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣
                commonIsXianUpdateParam.setCommonIdList(commonList);
                commonIsXianUpdateParam.setCommonIsXian(0);
                if (!CollectionUtils.isEmpty(commonList) && commonList.size() > 0) {
                    this.baseMapper.updateCommonIsXian3(commonIsXianUpdateParam);
                }
                activitySeckillGoodsMapper.delete(new LambdaQueryWrapper<ActivitySeckillGoodsEntity>()
                                          .eq(ActivitySeckillGoodsEntity::getSeckillId,param.getSeckillId()));
                goodsParam.setSeckillId(param.getSeckillId());
                goodsParam.setSeckillGoodsList(param.getSeckillGoodsList());
                goodsParam.setToken(param.getToken());
                activitySeckillGoodsService.addShopSeckillGoods(goodsParam);
            }
            return ResponseResult.success(seckillGoodsQueryResult.getSeckillId());
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

    }
}
